package main

import (
	"encoding/json"
	"gitee.com/showurl/mylive/config"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"github.com/thinkerou/favicon"
	"io/ioutil"
	"net/http"
	"os/exec"
	"strings"
)

var flvUrl = "http://live.msypy.xyz:7001/live/movie.flv"
var hlsUrl = "http://live.msypy.xyz:7002/live/movie.m3u8"

func init() {
	//if os.Getenv("env") == "" {
	//	flvUrl = "http://localhost:7001/live/movie.flv"
	//}
}
func IsMobile(userAgent string) bool {
	if len(userAgent) == 0 {
		return false
	}

	isMobile := false
	mobileKeywords := []string{"Mobile", "Android", "Silk/", "Kindle",
		"BlackBerry", "Opera Mini", "Opera Mobi"}

	for i := 0; i < len(mobileKeywords); i++ {
		if strings.Contains(userAgent, mobileKeywords[i]) {
			isMobile = true
			break
		}
	}

	return isMobile
}
func main() {
	logrus.SetLevel(logrus.DebugLevel)
	router := gin.Default()
	router.Static("/files", "templates/files")
	router.LoadHTMLGlob("templates/**/*")
	h := func(c *gin.Context) {
		if IsMobile(c.GetHeader("User-Agent")) {
			c.HTML(200, "index.mobile.html", gin.H{
				"title":    "直播",
				"playlist": config.Config.Playlist,
				"hlsUrl":   hlsUrl,
			})
		} else {
			c.HTML(200, "index.html", gin.H{
				"title":    "直播",
				"playlist": config.Config.Playlist,
				"flvUrl":   flvUrl,
			})
		}
	}
	router.GET("/", h)
	router.GET("/index", h)
	router.GET("/repush", func(c *gin.Context) {
		name, _ := c.GetQuery("name")
		ss, _ := c.GetQuery("ss")
		if ss == "" {
			ss = "0"
		}
		resp, err := http.Get("http://localhost:8090/control/get?room=movie")
		defer resp.Body.Close()
		if err != nil {
			panic(err)
		}
		body, _ := ioutil.ReadAll(resp.Body)
		logrus.Debug(name)
		r := &struct {
			Status int    `json:"status"`
			Data   string `json:"data"`
		}{}
		_ = json.Unmarshal(body, r)
		cmd := exec.Command("sh", "-c", "killall -9 ffmpeg; ffmpeg -re -ss "+ss+" -i "+name+" -vcodec copy -acodec copy -f flv \"rtmp://localhost:1935/live/"+r.Data+"\"")
		go func() {
			logrus.Info("执行命令：", strings.Join(cmd.Args, " "))
			err = cmd.Run()
			if err != nil {
				logrus.Error(err)
			}
		}()
		c.HTML(200, "index.html", gin.H{
			"title":    "直播",
			"playlist": config.Config.Playlist,
			"flvUrl":   flvUrl,
		})
	})
	router.Use(favicon.New("./favicon.ico"))
	panic(router.Run("0.0.0.0:8000"))
}
